package com.vvv.shortlink.admin.interceptor;


import com.vvv.shortlink.common.dto.UserInfoDTO;
import com.vvv.shortlink.common.toolkit.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author vvv
 * @date 2023-10-29 23 51
 * discription
 */
public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String id = request.getHeader("id");
        String username = request.getHeader("username");
        String realName = request.getHeader("realName");
        if (StringUtils.isEmpty(id)) {
            return true;
        }
        UserInfoDTO userInfoDTO = UserInfoDTO.builder()
                .id(Long.valueOf(id))
                .username(username)
                .realName(realName)
                .build();
        UserContext.saveUser(userInfoDTO);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();
    }
}
